package com.longxin.demoapp.experiments.experiment2.service.impl;

import android.Manifest;
import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.longxin.demoapp.R;
import com.longxin.demoapp.base.adapter.IBaseAdapter;
import com.longxin.demoapp.base.service.impl.IBaseServiceImpl;
import com.longxin.demoapp.experiments.experiment2.controller.Experiment2AddOrEditController;
import com.longxin.demoapp.experiments.experiment2.pojo.entity.Experiment2EntityUser;
import com.longxin.demoapp.experiments.experiment2.service.Experiment2Service;

import java.util.ArrayList;
import java.util.List;
import cn.hutool.core.util.StrUtil;


/**
 * @author Long
 * @version 1.0
 * @description:
 * @remarks:
 * @title ExperimentActivity2ServiceImpl
 * @date 2021/4/6 17:32
 */
public class Experiment2ServiceImpl extends IBaseServiceImpl implements Experiment2Service {
    public Experiment2ServiceImpl(Activity activity) {
        super(activity);
        //动态权限申请
        super.checkAuthority(Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS);
    }


    @Override
    public List<Experiment2EntityUser> query(String var) {
        List<Experiment2EntityUser> users = new ArrayList<>();
        Cursor cursor = activity.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);

        String phone, username;
        //while(cursor.moveToNext()){}这两种遍历方式一样
        assert cursor != null;
        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
//            username = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
//            phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

            username = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            //TODO

            if (StrUtil.isNotEmpty(var))
                if (!username.contains(var) && !phone.contains(var))
                    continue;

            Experiment2EntityUser user = new Experiment2EntityUser(username, phone);

            user.setUri(
                    //cursor.getColumnIndex(ContactsContract.Contacts._ID)联系人的资源ID
                    cursor.getLong(cursor.getColumnIndex(ContactsContract.Contacts._ID)),
                    //ContactsContract.Contacts.LOOKUP_KEY)联系人的LOOKUP_KEY
                    cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY))
            );
            users.add(user);
        }
        this.userNum(users.size());
        return users;
    }

    @Override
    public void initActivity(final IBaseAdapter adapter) {
        final List<Experiment2EntityUser> users = this.query(null);
        //得到ListView对象并设置适配器
        final ListView listView = (ListView) activity.findViewById(R.id.experiment_2_main_list_phones);
        listView.setAdapter(adapter);

        //长按弹出下拉菜单 ,此事件中可弹出下拉框
        /*listView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                TextView textViewUsername = (TextView) v.findViewById(R.id.experiment_2_list_item_username);
                TextView textViewPhone = (TextView) v.findViewById(R.id.experiment_2_list_item_phone);

                menu.add(0, 1, 0, "删除");//下拉菜单
                menu.add(0, 2, 0, "编辑");//下拉菜单
            }
        });*/


        //按钮事件设置
        activity.findViewById(R.id.experiment_2_main_btn_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeActivity(Experiment2AddOrEditController.class);
            }
        });
        activity.findViewById(R.id.experiment_2_main_btn_search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText editTextSearch = (EditText) activity.findViewById(R.id.experiment_2_main_box_search);
                adapter.setDatas(query(editTextSearch.getText().toString()));
            }
        });
    }

    @Override
    public boolean insert(Experiment2EntityUser user, final IBaseAdapter<Experiment2EntityUser> adapter) {
        //动态权限申请
        super.checkAuthority(Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS);
        adapter.addDatas(user);
        // 创建一个空的ContentValues
        ContentValues values = new ContentValues();
        Uri rawContactUri = activity.getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, values);

        try {
            assert rawContactUri != null;
            long rawContactId = ContentUris.parseId(rawContactUri);
            values.clear();

            values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
            // 内容类型
            values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
//            values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
            // 联系人名字
            values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, user.getUsername());
//            values.put(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, user.getUsername());
            // 向联系人URI添加联系人名字
            activity.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
            values.clear();

            values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
            values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
            // 联系人的电话号码
            values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, user.getPhone());
            // 电话类型
            values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
            // 向联系人电话号码URI添加电话号码
            activity.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
            values.clear();

            values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
            values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
            Toast.makeText(activity, "联系人数据添加成功！", Toast.LENGTH_SHORT).show();
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }

        return false;
    }

    @Override
    public boolean update(Experiment2EntityUser user, IBaseAdapter<Experiment2EntityUser> adapter) {
        //动态权限申请
        super.checkAuthority(Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS);
        // 创建一个空的ContentValues
        ContentValues values = new ContentValues();
        values.put(ContactsContract.Data.RAW_CONTACT_ID, user.getContactId());
        // 内容类型
        values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
        // 联系人名字
        values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, user.getUsername());
        // 向联系人URI添加联系人名字
        activity.getContentResolver().update(ContactsContract.Data.CONTENT_URI, values, ContactsContract.Data._ID  + " =?",  new String[]{user.getContactId().toString()});
        values.clear();

        values.put(ContactsContract.Data.RAW_CONTACT_ID, user.getContactId());
        values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
        // 联系人的电话号码
        values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, user.getPhone());
        // 电话类型
        values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
        // 向联系人电话号码URI添加电话号码
        activity.getContentResolver().update(ContactsContract.Data.CONTENT_URI, values, ContactsContract.Data._ID  + " =?",  new String[]{user.getContactId().toString()});
        values.clear();

        values.put(ContactsContract.Data.RAW_CONTACT_ID, user.getContactId());
        values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);

        Toast.makeText(activity, "联系人数据修改成功！", Toast.LENGTH_SHORT).show();
        return false;

    }


    @Override
    public boolean remove(Experiment2EntityUser user) {
        //动态权限申请
        super.checkAuthority(Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS);
        //方案一：删除对应联系人资源：包含整个联系人信息
        Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(user.getPhone()));
        Cursor cur = activity.getContentResolver().query(contactUri, null, null, null, null);
        try {
            if (cur.moveToFirst()) {
                do {
                    if (cur.getString(cur.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)).equalsIgnoreCase(user.getUsername())) {
                        String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
                        Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
                        activity.getContentResolver().delete(uri, null, null);
                    }
                } while (cur.moveToNext());
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            cur.close();
        }

        //方案二：删除对应数据，例如删除某个号码，不删除整个联系人
        /*ArrayList<ContentProviderOperation> ops = new ArrayList<>();
        ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
                .withSelection(ContactsContract.Data._ID + "=?", new String[]{String.valueOf(user.getContactId())})
                .build());

        try {
            activity.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
        } catch (OperationApplicationException e) {
            e.printStackTrace();
        } catch (RemoteException e) {
            e.printStackTrace();
        }*/

        //方案三：删除对应数据，例如删除某个号码，不删除整个联系人
//        activity.getContentResolver().delete(ContactsContract.RawContacts.CONTENT_URI, ContactsContract.Data._ID  + " =?",  new String[]{user.getContactId().toString()});
//        return false;
    }

    @Override
    public void userNum(int num) {
        //联系人数量
        ((TextView) activity.findViewById(R.id.experiment_2_main_text_user_num)).setText("共" + num + "位联系人");
    }
}
